package cn.jbolt.wechat.service;

import cn.jbolt.core.base.JBoltMsg;
import cn.jbolt.core.cache.JBoltQiniuCache;
import cn.jbolt.core.common.config.JBoltUploadFolder;
import cn.jbolt.core.consts.JBoltConst;
import cn.jbolt.core.db.sql.Sql;
import cn.jbolt.core.enumutil.JBoltEnum;
import cn.jbolt.core.model.Qiniu;
import cn.jbolt.core.model.QiniuBucket;
import cn.jbolt.core.service.base.JBoltBaseService;
import cn.jbolt.core.util.JBoltDateUtil;
import cn.jbolt.core.util.JBoltRealUrlUtil;
import cn.jbolt.wechat.cache.JBoltWechatConfigCache;
import cn.jbolt.wechat.common.WechatMediaType;
import cn.jbolt.wechat.common.WechatApiResult;
import cn.jbolt.wechat.common.mp.WechatMpContext;
import cn.jbolt.wechat.model.WechatMedia;
import cn.jbolt.wechat.model.WechatMpinfo;
import com.google.gson.Gson;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Okv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishArticles;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishItem;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishList;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialCountResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class JBoltWechatMediaService extends JBoltBaseService<WechatMedia> {
    private WechatMedia dao = new WechatMedia().dao();
    @Inject
    private JBoltWechatConfigService wechatConfigService;
    @Inject
    private JBoltWechatMpinfoService wechatMpinfoService;

    @Override
    protected WechatMedia dao() {
        return dao;
    }

    /**
     * 后台分页管理查询
     *
     * @param mpId
     * @param type
     * @param keywords
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public Page<WechatMedia> paginateAdminList(Long mpId, String type, String keywords, Integer pageNumber,
                                               int pageSize) {
        if (notOk(mpId) || notOk(type)) {
            return emptyPage(pageSize);
        }
        Sql sql = selectSql().page(pageNumber, pageSize);
        sql.eq("mp_id", mpId);
        sql.eq("type", type);
        sql.likeMulti(keywords, "title", "digest");
        sql.desc("update_time");
        return paginate(sql);
    }

    /**
     * 同步素材库
     *
     * @param mpId
     * @return
     */
    public Ret syncAll(Long mpId) {
        return syncDatas(mpId, false);
    }

    /**
     * 同步素材库
     *
     * @param mpId
     * @return
     */
    public Ret syncNewDatas(Long mpId) {
        return syncDatas(mpId,  true);
    }

    /**
     * 同步素材库
     *
     * @param mpId
     * @param onlyNew       是否仅同步新数据
     * @return
     */
    public Ret syncDatas(Long mpId,  boolean onlyNew) {
        if (notOk(mpId) ) {
            return fail(JBoltMsg.PARAM_ERROR);
        }
        WechatMpinfo mpinfo = wechatMpinfoService.findById(mpId);
        if (mpinfo == null) {
            return fail("微信公众平台信息不存在");
        }
        String appId = JBoltWechatConfigCache.me.getAppId(mpId);
        if (StrKit.isBlank(appId)) {
            return fail(mpinfo.getName() + "基础配置异常:APPID");
        }
        WechatMpContext.switchTo(appId);
        try {

            WechatApiResult<WxMpMaterialCountResult> res = WechatMpContext.getMaterialCount();
            if (res.isSuccess() == false) {
                return fail(res.getMsg());
            }
            WxMpMaterialCountResult data = res.getData();
            Ret ret = syncNews(mpId, onlyNew);
            if (ret.isFail()) {
                return ret;
            }

            ret = syncByType(mpId,  WechatMediaType.IMG.getValue(), data.getImageCount(), onlyNew);
            if (ret.isFail()) {
                return ret;
            }
            ret = syncByType(mpId,  WechatMediaType.VOICE.getValue(), data.getVoiceCount(), onlyNew);
            if (ret.isFail()) {
                return ret;
            }
            ret = syncByType(mpId,   WechatMediaType.VIDEO.getValue(), data.getVideoCount(), onlyNew);
            if (ret.isFail()) {
                return ret;
            }
        } catch (Exception e) {
            return fail(e.getMessage());
        } finally {
            WechatMpContext.switchOver();
        }
        return SUCCESS;
    }

    /**
     * 同步指定类型素材
     *
     * @param mpId
     * @param type
     * @param totalCount
     * @param newDatas
     * @return
     */
    private Ret syncByType(Long mpId, String type, Integer totalCount, boolean newDatas) {
        if (totalCount == null || totalCount < 0) {
            return fail("同步[" + type + "]素材异常,总数参数异常");
        }
        if (totalCount == 0) {
            return SUCCESS;
        }
        if (!newDatas) {
            //清空数据
            deleteByType(mpId, type);
        }
        //分页同步
        return syncMediaByPages(mpId, totalCount, type, newDatas);
    }

    /**
     * 同步除了news之外的 其他指定类型
     *
     * @param mpId
     * @param totalCount
     * @param type
     * @param newDatas
     * @return
     */
    private Ret syncMediaByPages(Long mpId,Integer totalCount, String type, boolean newDatas) {
        int pageSize = 20;
        int pageTotal = totalCount / pageSize + (totalCount % pageSize > 0 ? 1 : 0);
        Ret ret = null;
        List<WechatMedia> wechatMedias = new ArrayList<WechatMedia>();
        for (int pageNumber = 1; pageNumber <= pageTotal; pageNumber++) {
            ret = syncMediaOnePage(mpId, type, pageNumber, pageSize, wechatMedias, newDatas);
            if (ret.isFail()) {
                if (newDatas && "exist".equals(ret.getStr("msg"))) {
                    break;
                }
                return ret;
            }
            if (wechatMedias.size() >= 100) {
                batchSave(wechatMedias);
                wechatMedias.clear();
            }
        }
        if (wechatMedias.size() > 0) {
            //最后一步保存释放
            batchSave(wechatMedias);
            wechatMedias.clear();
            wechatMedias = null;
        }
        return SUCCESS;

    }

    /**
     * 同步图文
     *
     * @param mpId
     * @param newDatas
     * @return
     */
    private Ret syncNews(Long mpId, boolean newDatas) {
        if (!newDatas) {
            //清空数据
            deleteByType(mpId, WechatMediaType.NEWS.getValue());
        }
        //分页同步
        return syncNewsByPages(mpId,  newDatas);
    }

    /**
     * 按照公众号ID和类型删除素材
     *
     * @param mpId
     * @param type
     * @return
     */
    private Ret deleteByType(Long mpId, String type) {
        return deleteBy(Okv.by("mp_id", mpId).set("type", type));
    }

    /**
     * 分页同步图文素材
     *
     * @param mpId
     * @param newDatas
     * @return
     */
    private Ret syncNewsByPages(Long mpId, boolean newDatas) {
        int pageSize = 20;
        int pageNumber = 1;
        Ret ret = null;
        List<WechatMedia> wechatMedias = new ArrayList<WechatMedia>();
        do {
            ret = syncNewOnePage(mpId, pageNumber++, pageSize, wechatMedias, newDatas);
            if (ret.isFail()) {
                return ret;
            }
            if (wechatMedias.size() >= 100) {
                batchSave(wechatMedias);
                wechatMedias.clear();
            }
        } while (ret.isFail() == false && ret.getInt("count") == pageSize);

        if (wechatMedias.size() > 0) {
            //最后一步保存释放
            batchSave(wechatMedias);
            wechatMedias.clear();
            wechatMedias = null;
        }
        return SUCCESS;
    }

    /**
     * 同步一页的图文素材
     *
     * @param mpId
     * @param pageNumber
     * @param pageSize
     * @param newDatas
     * @return
     */
    private Ret syncNewOnePage(Long mpId, int pageNumber, int pageSize, List<WechatMedia> wechatMedias, boolean newDatas) {
        int offset = (pageNumber - 1) * pageSize;

        WechatApiResult<WxMpFreePublishList> res = WechatMpContext.getPublishRecords(offset, pageSize, false);
        if (!res.isSuccess()) {
            return fail(res.getMsg());
        }
        WxMpFreePublishList data = res.getData();
        Integer itemCount = data.getItemCount();
        if (itemCount == null) {
            return fail("同步图文素材异常，当前同步到第[" + pageNumber + "]页");
        }
        if (itemCount > 0) {
            Ret ret = null;
            for (WxMpFreePublishItem item : data.getItems()) {
                ret = processOneItemNews(mpId, item, wechatMedias, newDatas);
                if (ret.isFail()) {
                    return ret;
                }
            }
        }
        return Ret.ok("count", itemCount);
    }

    /**
     * 同步一页的指定类型的素材
     *
     * @param mpId
     * @param type
     * @param pageNumber
     * @param pageSize
     * @param wechatMedias
     * @param newDatas
     * @return
     */
    private Ret syncMediaOnePage(Long mpId, String type, int pageNumber, int pageSize, List<WechatMedia> wechatMedias, boolean newDatas) {
        int offset = (pageNumber - 1) * pageSize;

        WechatApiResult<WxMpMaterialFileBatchGetResult> res = WechatMpContext.getMaterialRecords(type, offset, pageSize);
        if (!res.isSuccess()) {
            return fail(res.getMsg());
        }

        WxMpMaterialFileBatchGetResult data = res.getData();

        Integer itemCount = data.getItemCount();
        if (itemCount == null) {
            return fail("同步[" + type + "]素材异常，当前同步到第[" + pageNumber + "]页");
        }
        if (itemCount > 0) {
            List<WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem> items = data.getItems();

            for (WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem item : items) {
                if (newDatas) {
                    boolean exist = checkExistMedia(mpId, type, item.getMediaId());
                    if (exist) {
                        return fail("exist");
                    }
                }
                wechatMedias.add(convertToMedia(mpId, type, item));
            }

        }
        return SUCCESS;
    }

    private boolean checkExistMedia(Long mpId, String type, String mediaId) {
        Sql sql = selectSql().selectId().eqQM("mp_id", "type", "media_id").first();
        Integer existId = queryInt(sql, mpId, type, mediaId);
        return isOk(existId);
    }

    /**
     * 处理一个Item
     *
     * @param mpId
     * @param type
     * @param media
     * @param
     */
    private WechatMedia convertToMedia(Long mpId, String type, WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem media) {
        String mediaId = media.getMediaId();
        WechatMedia wechatMedia = new WechatMedia();
        String name = media.getName();

        wechatMedia.autoProcessIdValue();
        wechatMedia.setTitle(name);
        wechatMedia.setUrl(media.getUrl());
        wechatMedia.setType(type);
        wechatMedia.setMediaId(mediaId);
        wechatMedia.setMpId(mpId);
        wechatMedia.setUpdateTime(media.getUpdateTime());
        return wechatMedia;
    }

    /**
     * 解析处理图文的一个Item 下的单图文和多图文
     *
     * @param mpId
     * @param item
     * @param wechatMedias
     * @param newDatas
     * @return
     */
    private Ret processOneItemNews(Long mpId, WxMpFreePublishItem item, List<WechatMedia> wechatMedias, boolean newDatas) {
        String mediaId = item.getArticleId();
        List<WxMpFreePublishArticles> articles = item.getContent().getNewsItem();
        for (WxMpFreePublishArticles article : articles) {
            if (newDatas) {
                if (checkExistNews(mpId, article.getUrl())) {
                    continue;
                }
            }
            if ("分享一篇文章。".equals(article.getDigest())) {
                continue;
            }
            wechatMedias.add(covertToNews(article, mpId, mediaId, item.getUpdateTime()));
        }
        return SUCCESS;
    }

    /**
     * 检测图文信息是否存在
     *
     * @param mpId
     * @param url
     * @return
     */
    private boolean checkExistNews(Long mpId, String url) {
        Sql sql = selectSql().selectId().eqQM("mp_id", "type", "url").first();
        Integer existId = queryInt(sql, mpId, WechatMediaType.NEWS, url);
        return isOk(existId);
    }

    /**
     * 将JSON转WechatMedia中的news
     *
     * @param article
     * @param mpId
     * @param mediaId
     * @return
     */
    private WechatMedia covertToNews(WxMpFreePublishArticles article, Long mpId, String mediaId, String updateTime) {
        WechatMedia wechatMedia = new WechatMedia();
        wechatMedia.autoProcessIdValue();
        wechatMedia.setAuthor(article.getAuthor());
        wechatMedia.setTitle(article.getTitle());
        wechatMedia.setDigest(article.getDigest());
        wechatMedia.setUrl(article.getThumbUrl());
        wechatMedia.setServerUrl(article.getUrl());
        wechatMedia.setType(WechatMediaType.NEWS.getValue());
        wechatMedia.setThumbMediaId(article.getThumbMediaId());
        wechatMedia.setMediaId(mediaId);
        wechatMedia.setContentSourceUrl(article.getContentSourceUrl());
        wechatMedia.setMpId(mpId);
        if (updateTime != null) {
            wechatMedia.setUpdateTime(new Date(Long.parseLong(updateTime) * 1000L));
        } else {
            wechatMedia.setUpdateTime(new Date());
        }
        return wechatMedia;
    }

    //判断是否正在执行每隔一分钟的下载任务
    public static volatile boolean downloading = false;


    /**
     * 执行同步下载素材元数据
     */
    public Ret uploadWechatMedia(Long mpId, Long bucketId) {
        if (hasNotOk(mpId, bucketId)) {
            return fail(JBoltMsg.PARAM_ERROR);
        }
        QiniuBucket bucket = JBoltQiniuCache.me.getBucket(bucketId);
        if (bucket == null) {
            return fail("Bucket不存在");
        }
        if (bucket.getEnable() == false) {
            return fail("Bucket未开启");
        }
        WechatMpinfo wechatMpinfo = wechatMpinfoService.findById(mpId);
        if (wechatMpinfo == null) {
            return fail("当前操作的微信公众平台信息不存在");
        }
        System.out.println("调用微信公众号素材下载任务 start");
        if (downloading) {
            System.out.println("任务执行中，等待一分钟后重新调用...");
            return fail("任务执行中，等待一分钟后重新调用...");
        }
        String appId = JBoltWechatConfigCache.me.getAppId(mpId);
        downloading = true;
        WechatMpContext.switchTo(appId);
        //开始执行下载 首先获取需要同步现在的media
        List<WechatMedia> needSyncUploadMedias = null;
        Ret ret = null;
        try {
            do {
                needSyncUploadMedias =  getNeedDownloadMedias(mpId, 500);

                if (needSyncUploadMedias != null && needSyncUploadMedias.size() > 0) {
                    System.out.println("找到[" + needSyncUploadMedias.size() + "]个需要下载的任务");
                    ret = syncUploadMedias(needSyncUploadMedias, bucket);
                } else {
                    ret = success("没有需要下载的任务了");
                    System.out.println("没有需要下载的任务了");
                }
            } while (needSyncUploadMedias != null && needSyncUploadMedias.isEmpty() == false && ret.isFail() == false);

            downloading = false;
            System.out.println("调用微信公众号素材下载任务 end");
        } finally {
            WechatMpContext.switchOver();
        }

        return ret;
    }

    /**
     * 将素材同步到七牛
     *
     * @param inputStream
     * @param path
     * @return
     */
    public Ret uploadWechatMediaToQiniu(QiniuBucket bucket, InputStream inputStream, String path) {
        Qiniu qiniu = JBoltQiniuCache.me.get(bucket.getQiniuId());
        String accessKey = qiniu.getAk();
        String secretKey = qiniu.getSk();
        String bucketSn = bucket.getName();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucketSn);

        System.out.println("开始上传到七牛：:" + path);

        try {
            Configuration cfg = new Configuration(Region.autoRegion());
            cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
            UploadManager uploadManager = new UploadManager(cfg);
            Response response = uploadManager.put(inputStream, path, upToken, null, null);
            String body = response.bodyString();
            System.out.println("响应：" + body);
            DefaultPutRet putRet = new Gson().fromJson(body, DefaultPutRet.class);
            System.out.println("上传成功：" + putRet.key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return SUCCESS;
    }


    /**
     * 下载素材
     *
     * @param needDownloadMedias
     */
    private Ret syncUploadMedias(List<WechatMedia> needDownloadMedias, QiniuBucket bucket) {
        Ret ret = null;
        for (WechatMedia media : needDownloadMedias) {
            ret = uploadMedia(bucket, media);
            if (ret.isFail()) {
                return ret;
            }
        }
        return success("素材下载成功：" + needDownloadMedias.size() + "个");
    }

    /**
     * 下载 meida
     *
     * @param bucket
     * @param media
     */
    private Ret uploadMedia( QiniuBucket bucket, WechatMedia media) {
        try {

            WechatMediaType wechatMediaType = JBoltEnum.getEnumObjectByValue(WechatMediaType.class, media.getType());
            Ret ret;
            switch (wechatMediaType) {
//                case NEWS:
//                    break;
                case VIDEO:
                    ret = uploadVideo(bucket, media);
                    break;
                case IMG:
                case VOICE:
                    ret = uploadImageOrVoice(bucket, media);
                    break;
            }

            String mediaId = media.getType().equals(WechatMediaType.NEWS) ? media.getThumbMediaId() : media.getMediaId();


//            if (stream != null) {
//
//                String fileFolderPath = JFinal.me().getConstants().getBaseUploadPath() + "/" + JBoltUploadFolder.WECHAT_MEDIA + "/" + media.getMpId() + "/" + media.getType() + "/" + todayFolder;
//                if (media.getType().equals(WechatMediaType.VIDEO.getValue())) {
//                    String json = IOUtils.toString(stream);
//                    if (StrKit.notBlank(json) && json.indexOf("errcode") != -1 && json.indexOf("45009") != -1) {
//                        System.out.println("永久素材下载限额已超，请登录后清零");
//                        return fail("永久素材下载限额已超，请登录后清零");
//                    }
//
//                    JSONObject jsonObject = JSON.parseObject(json);
//                    if (jsonObject.containsKey("down_url")) {
//                        String videoUrl = jsonObject.getString("down_url");
//                        String description = jsonObject.getString("description");
//                        media.setServerUrl(videoUrl);
//                        if (StrKit.notBlank(description)) {
//                            media.setDigest(description);
//                        }
//                        media.update();
//                    }
//                } else {
//                    String filename = null;
//
//                    if (wechatMediaType != null) {
//                        switch (wechatMediaType) {
//                            case NEWS:
//                                filename = media.getMpId() + "_" + media.getId() + "_" + mediaId + ".jpg";
//                                break;
//                            case IMG:
//                                filename = media.getMpId() + "_" + media.getId() + "_" + mediaId + ".jpg";
//                                break;
//                            case VOICE:
//                                filename = media.getMpId() + "_" + media.getId() + "_" + mediaId + ".mp3";
//                                break;
//                        }
//                    }
//                    String filePath = fileFolderPath + "/" + filename;
//                    boolean isAbs = FileUtil.isAbsolutePath(filePath);
//                    String absPath = isAbs ? filePath : (PathKit.getWebRootPath() + "/" + filePath);
//
//                    if (FileUtil.exist(absPath)) {
//                        media.setServerUrl(filePath);
//                        media.update();
//                        return SUCCESS;
//                    } else {
//                        if (!isAbs) {
//                            fileFolderPath = PathKit.getWebRootPath() + "/" + fileFolderPath;
//                        }
//                        FileUtil.mkdir(fileFolderPath);
//                    }
//                    File targetFile = new File(absPath);
//                    IOUtils.toFile(stream, targetFile);
//                    if (targetFile.exists()) {
//                        if (targetFile.length() == 0) {
//                            targetFile.delete();
//                            media.setServerUrl("assets/img/uploadimg.png");
//                            media.update();
//                        } else {
//                            String type = FileTypeUtil.getType(targetFile);
//                            if (StrKit.isBlank(type)) {
//                                String json = FileUtil.readUtf8String(absPath);
//                                if (StrKit.notBlank(json) && json.indexOf("errcode") != -1 && json.indexOf("45009") != -1) {
//                                    System.out.println("永久素材下载限额已超，请登录后清零");
//                                } else {
//                                    media.setServerUrl(filePath);
//                                    media.update();
//                                }
//                            } else {
//                                media.setServerUrl(filePath);
//                                media.update();
//                            }
//
//                        }
//
//
//                    }
//                }
//
//            }
        } catch (Exception e) {
            return fail("");
        }
        return SUCCESS;

    }



    /**
     * 下载图片和声音
     *
     * @param bucket
     * @param media
     * @return
     */
    private Ret uploadVideo(QiniuBucket bucket, WechatMedia media) {
        try {
            WxMpMaterialVideoInfoResult videoInfo = WechatMpContext.SERVICE.getMaterialService().materialVideoInfo(media.getMediaId());
            System.out.println(videoInfo.getDownUrl());
            media.setServerUrl(videoInfo.getDownUrl());
            media.update();
            return SUCCESS;
        } catch (WxErrorException e) {
            e.printStackTrace();
            return fail("素材[" + media.getMediaId() + "]上传到七牛失败");
        }

    }
    /**
     * 下载图片和声音
     *
     * @param bucket
     * @param media
     * @return
     */
    private Ret uploadImageOrVoice(QiniuBucket bucket, WechatMedia media) {

        try {
            String path = "wechat/mp/" + media.getMpId() + "/"
                    + media.getType() + "/" + JBoltDateUtil.format(new Date(), "yyMMdd") + JBoltConst.SLASH + media.getTitle();
            InputStream inputStream = WechatMpContext.SERVICE.getMaterialService().materialImageOrVoiceDownload(media.getMediaId());
            uploadWechatMediaToQiniu(bucket, inputStream, path);
            media.setServerUrl(bucket.getDomainUrl() + JBoltConst.SLASH + path);
            media.update();
            return SUCCESS;
        } catch (WxErrorException e) {
            e.printStackTrace();
            return fail("素材[" + media.getMediaId() + "]上传到七牛失败");
        }

    }

    /**
     * 获取指定个数的需要下载素材资源的media
     *
     * @param count
     * @return
     */
    private List<WechatMedia> getNeedDownloadMedias(Long mpId, int count) {
        Sql sql = selectSql().eqQM("mp_id").isNull("server_url").firstPage(count);
        return find(sql.toSql(), mpId);
    }

    /**
     * 删除指定公众平台的
     *
     * @param mpId
     * @return
     */
    public Ret deleteByMpId(Long mpId) {
        return deleteBy(Okv.by("mp_id", mpId));
    }

    /**
     * 在回复内容选择处选择一条数据使用
     *
     * @param mpId
     * @param id
     * @return
     */
    public Ret getReplyChooseInfo(Long mpId, Long id) {
        if (notOk(mpId) || notOk(id)) {
            return fail(JBoltMsg.PARAM_ERROR);
        }
        WechatMpinfo wechatMpinfo = wechatMpinfoService.findById(mpId);
        if (wechatMpinfo == null) {
            return fail("关联微信公众平台信息不存在");
        }
        WechatMedia wechatMedia = findById(id);
        if (wechatMedia == null) {
            return fail(JBoltMsg.DATA_NOT_EXIST);
        }
        if (wechatMedia.getMpId().longValue() != mpId.longValue()) {
            return fail(JBoltMsg.PARAM_ERROR + ":mpId");
        }
        String serverUrl = wechatMedia.getServerUrl();
        if (isOk(serverUrl)) {
            if (wechatMedia.getType().equals(WechatMediaType.IMG.getValue()) || wechatMedia.getType().equals(WechatMediaType.NEWS)) {
                wechatMedia.put("realImgUrl", JBoltRealUrlUtil.getImage(serverUrl));
            } else if (wechatMedia.getType().equals(WechatMediaType.VOICE.getValue())) {
                wechatMedia.put("realVoiceUrl", JBoltRealUrlUtil.get(serverUrl, null));
            }
        }
        return success(wechatMedia, JBoltMsg.SUCCESS);
    }

    @Override
    protected int systemLogTargetType() {
        // TODO Auto-generated method stub
        return 0;
    }


}
